package cc.chinagps.gateway.unit.eg.upload.cmds;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.seg.lib.util.Util;

import cc.chinagps.gateway.buff.CommandBuff;
import cc.chinagps.gateway.log.LogManager;
import cc.chinagps.gateway.seat.cmd.CmdResponseUtil;
import cc.chinagps.gateway.seat.cmd.ServerToUnitCommand;
import cc.chinagps.gateway.unit.UnitServer;
import cc.chinagps.gateway.unit.UnitSocketSession;
import cc.chinagps.gateway.unit.eg.define.EGDefines;
import cc.chinagps.gateway.unit.eg.pkg.EGPackage;
import cc.chinagps.gateway.unit.eg.util.EGPkgUtil;
import cc.chinagps.gateway.unit.eg.util.EGTimeFormatUtil;
import cc.chinagps.gateway.util.Constants;

public class Cmd81 extends CheckLoginHandler {
	private Logger logger_debug = Logger.getLogger(LogManager.LOGGER_NAME_DEBUG);

	@Override
	public boolean handlerPackageSessionChecked(EGPackage pkg, UnitServer server, UnitSocketSession session)
			throws Exception {
		String callLetter = session.getUnitInfo().getCallLetter();
		byte data[] = pkg.getData();
		int pos = 0;
		String collectTime = EGTimeFormatUtil.getDateTime(pkg.getData(), pos, 6);
		pos += 6;
		int responseMsgSn = Util.getShort(data, pos);
		pos += 2;
		String responseText = new String(data, pos, data.length - 8, EGDefines.CHARSET);

		logger_debug.debug("[EG][Cmd81][" + callLetter + "] recv cmd response,collectTime:" + collectTime + ";serialNo:"
				+ responseMsgSn + ";responseText:" + responseText);
		String[] txtArr = responseText.split("\\$");
		int result = 0;
		String params = null;
		if (txtArr.length == 4) {
			String resultTxt = txtArr[3];
			String resArr[] = resultTxt.split(":");
			if (resArr.length >= 2) {
				String resContent = resultTxt.substring(6);
				params = resContent;
				if (StringUtils.isNotBlank(resContent)) {
					if ("01".equals(resContent.substring(0, 2))) {
						result = 1;
					}
				}
			}
		}
		String cacheSN = EGPkgUtil.getCmdCacheSn(callLetter, responseMsgSn);
		ServerToUnitCommand cache = server.getServerToUnitCommandCache().getAndRemoveCommand(cacheSN);
		CommandBuff.CommandResponse.Builder builder = CommandBuff.CommandResponse.newBuilder();
		builder.setCallLetter(callLetter);
		if (result == 1) {
			builder.setResult(Constants.RESULT_SUCCESS);
			if (StringUtils.isNotBlank(params)) {
				builder.addParams(params);
			}
		} else {
			builder.setResult(Constants.RESULT_UNIT_ACK_FAIL);
			if (StringUtils.isNotBlank(params)) {
				builder.addParams(params);
			}
		}
		if (cache != null) {
			CommandBuff.Command usercmd = cache.getUserCommand();
			builder.setSn(usercmd.getSn());
			builder.setCmdId(usercmd.getCmdId());
			CmdResponseUtil.simpleCommandResponse(cache, builder);
		}
		return true;
	}
}